package com.encryption.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.encryption.logic.ManageActionConstant;
import com.encryption.logic.ManageActionLogHelper;
import com.encryption.logic.UserConstant;
import com.encryption.model.User;

/**
 * A data access object (DAO) providing persistence and search support for User
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see com.encryption.model.User
 * @author MyEclipse Persistence Tools
 */

public class UserDAO extends BaseHibernateDAO {
	private static final Logger log = LoggerFactory.getLogger(UserDAO.class);
	// property constants
	public static final String LOGIN_NAME = "loginName";
	public static final String PASSWORD = "password";
	public static final String REAL_NAME = "realName";
	public static final String MOBILE = "mobile";
	public static final String EMAIL = "email";
	public static final String POST = "post";
	public static final String ADUIT_STATE = "aduitState";

	public void save(User transientInstance) {
		log.debug("saving User instance");
		try {
			getSession().save(transientInstance);
			getSession().flush();
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		} catch (Throwable te) {
			log.error("save failed", te);
		}
	}

	public void update(User transientInstance) {
		log.debug("updating User instance");
		try {
			getSession().update(transientInstance);
			flush(transientInstance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		} catch (Throwable te) {
			log.error("update failed", te);
		}
	}

	private void flush(User user) {
		try {
			getSession().flush();
		} catch (Exception e) {
			log.debug("", e);
		}
		getSession().evict(user);
	}

	public void delete(User persistentInstance) {
		log.debug("deleting User instance");
		try {
			persistentInstance.setAduitState(UserConstant.STATE_DELETE);
			merge(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public void deleteById(String id) {
		log.debug("deleting User instance");
		try {
			String deleteSql = "update user set aduit_state="
					+ UserConstant.STATE_DELETE + " where id=" + id;
			SQLQuery query = getSession().createSQLQuery(deleteSql);
			query.executeUpdate();
			User user = findById(Integer.parseInt(id));

			flush(user);
			ManageActionLogHelper.addLog(
					ManageActionConstant.ACTION_DELETE_USER, user.toString());
			log.debug(deleteSql);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public User findById(java.lang.Integer id) {
		log.debug("getting User instance with id: " + id);
		try {
			User instance = (User) getSession().get(
					"com.encryption.model.User", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample2(User instance) {
		log.debug("finding User instance by example");
		try {
			List results = getSession()
					.createCriteria("com.encryption.model.User")
					.add(Example.create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding User instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from User as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByLoginName(Object loginName) {
		return findByProperty(LOGIN_NAME, loginName);
	}

	public List findByPassword(Object password) {
		return findByProperty(PASSWORD, password);
	}

	public List findByRealName(Object realName) {
		return findByProperty(REAL_NAME, realName);
	}

	public List findByMobile(Object mobile) {
		return findByProperty(MOBILE, mobile);
	}

	public List findByEmail(Object email) {
		return findByProperty(EMAIL, email);
	}

	public List findByPost(Object post) {
		return findByProperty(POST, post);
	}

	public List findByAduitState(Object aduitState) {
		return findByProperty(ADUIT_STATE, aduitState);
	}

	public List findAll() {
		log.debug("finding all User instances");
		try {
			String queryString = "from User";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public User merge(User detachedInstance) {
		log.debug("merging User instance");
		try {
			User result = (User) getSession().merge(detachedInstance);
			flush(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(User instance) {
		log.debug("attaching dirty User instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(User instance) {
		log.debug("attaching clean User instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	/**
	 * 根据condition对用户表查询
	 * 
	 * @param instance
	 * @return
	 */
	public List<User> findByExample(List<Condition> conditions) {
		log.debug("finding User instance by example");
		try {
			conditions.add(createDeleteCondition());

			Criteria criteria = getSession().createCriteria(User.class);
			// 设置查询条件
			BaseHibernateDAO.addCriteria(conditions, criteria);
			criteria.addOrder(Order.desc("registerTime"));

			List<User> results = criteria.list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public int findByExample4Count(List<Condition> conditions) {
		log.debug("finding User instance by example");
		try {
			conditions.add(createDeleteCondition());

			Criteria criteria = getSession().createCriteria(User.class);
			// 设置查询条件
			BaseHibernateDAO.addCriteria(conditions, criteria);
			criteria.addOrder(Order.desc("registerTime"));

			List<User> results = criteria.list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results.size();
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	/**
	 * 分页查询用户表
	 */
	public List<User> findByExample4Page(List<Condition> conditions, int page,
			int pageSize) {
		log.debug("finding User instance by example");
		try {
			conditions.add(createDeleteCondition());
			Criteria criteria = getSession().createCriteria(User.class);
			criteria.addOrder(Order.desc("registerTime"));
			// 设置查询条件
			BaseHibernateDAO.addCriteria(conditions, criteria);
			criteria.setFirstResult(page);
			criteria.setFetchSize(pageSize);
			List<User> results = criteria.list();

			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	private Condition createDeleteCondition() {
		Condition cond = new Condition();
		cond.setCode("aduitState");
		cond.setOperation(">");
		cond.setValue(UserConstant.STATE_DELETE);

		return cond;
	}

	private static UserDAO userDao = null;

	public static UserDAO getUserDAO() {
		if (null == userDao) {
			userDao = new UserDAO();
		}
		return userDao;
	}

}